/**
 * 
 */
package com.firmye.codereposboot.config.security;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;
import java.util.Iterator;

/**
 * @Author Firmye
 * @Date 2017年12月7日 上午1:29:09
 * 
 * @Description 4.自定义决策管理器
 */
// @Component
public class CustomAccessDecisionManager implements AccessDecisionManager {

	protected Log log = LogFactory.getLog(this.getClass());

	/**
	 * @Author Firmye
	 * @Date 2017年12月7日 上午1:29:34
	 *
	 * @Description 决策方法，判断用户请求是否在用户权限表中
	 */
	@Override
	public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
		if (null == configAttributes || configAttributes.size() <= 0) {
			return;
		}

		Iterator<ConfigAttribute> iterator = configAttributes.iterator();

		while (iterator.hasNext()) {
			ConfigAttribute ca = iterator.next();
			String needRole = ((SecurityConfig) ca).getAttribute();

			// ga为用户所被赋予的权限，needRole为访问相应的资源应该具有的权限
			for (GrantedAuthority ga : authentication.getAuthorities()) {
				if (needRole.trim().equals(ga.getAuthority().trim())) {
					log.info("=====> The current user has authority");
					return;
				}
			}
		}

		throw new AccessDeniedException("=====> Permission Denied");

	}

	/**
	 * @Author Firmye
	 * @Date 2017年12月7日 上午1:29:34
	 *
	 * @Description
	 */
	@Override
	public boolean supports(ConfigAttribute attribute) {
		// TODO Auto-generated method stub
		return true;
	}

	/**
	 * @Author Firmye
	 * @Date 2017年12月7日 上午1:29:34
	 *
	 * @Description
	 */
	@Override
	public boolean supports(Class<?> clazz) {
		// TODO Auto-generated method stub
		return true;
	}

}
